package com.easyj.base.storage.service.impl;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.easyj.base.common.storage.FileInfo;
import com.easyj.base.common.storage.PathFormat;
import com.easyj.base.constant.ConstantProperties;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.exception.FileStoreException;
import com.easyj.base.storage.service.StorageConstants;
import com.easyj.base.storage.service.StorageService;


/**
 * 保存上传文件,保存到ali oss,-----
 * @author hjf
 *
 */
@Configuration
@ConditionalOnProperty(name = "upload.storage-type", havingValue = "alioss")
public class AliOssStorageService {
	@Service
	public class AliOssStorageServiceImpl implements StorageService{
		
		public Logger log =  LoggerFactory.getLogger(getClass());

		
		/**
		 * 保存流程申请文件 root下的applyfiles目录
		 * @param file
		 * @param request
		 * @return
		 * @throws FileStoreException 
		 */
		@Override
		public  FileInfo storeAppendFile(MultipartFile file) throws FileStoreException {
			StorageConstants.CheckAppendFile(file);//check...
			return localStore(file,StorageConstants.AppendDir);
		}
		
		
		@Override
		public FileInfo storeImageFile(MultipartFile file) throws FileStoreException{
			StorageConstants.checkImageFile(file);//check...
			return localStore(file,StorageConstants.ImageDir);
		}
		
		
		
		@Override
		public FileInfo storeAvatarFile(MultipartFile file) throws FileStoreException{
			StorageConstants.checkAvatarFile(file);//check...
			//缩小图像....
			return localStore(file,StorageConstants.AvatarDir);
		}
		
		
		
		/**
		 * 删除文件
		 */
		@Override
		public boolean deleteFile(String path){
			OSS ossClient = new OSSClientBuilder().build(ConstantProperties.ALIOSS_END_POINT, ConstantProperties.ALIOSS_ACCESS_KEY_ID, ConstantProperties.ALIOSS_ACCESS_KEY_SECRET);
			ossClient.deleteObject(ConstantProperties.ALIOSS_BUCKET_NAME, path);
			// 关闭OSSClient。
			ossClient.shutdown();
			return true;
		}
		
		@Override
		public String saveExcelImpResult(Workbook wb, String fileType) throws FileStoreException {
			
			String savePath = PathFormat.parse(StorageConstants.ImportResultDir+"/{yyyy}{mm}{dd}/");
			//新文件名时间+8位rand数
			String uqstr=PathFormat.parse("{time}{rand:8}");
			String fileName="err_"+uqstr+"."+fileType;
			
            savePath=savePath+fileName;//filePath
			
			OSS ossClient = new OSSClientBuilder().build(ConstantProperties.ALIOSS_END_POINT, ConstantProperties.ALIOSS_ACCESS_KEY_ID, ConstantProperties.ALIOSS_ACCESS_KEY_SECRET);
			
			// 上传网络流。
			 ByteArrayOutputStream out = new ByteArrayOutputStream();
		     try  {
		    	 
			     wb.write(out);
				 ossClient.putObject(new PutObjectRequest(ConstantProperties.ALIOSS_BUCKET_NAME, savePath, new ByteArrayInputStream(out.toByteArray())));
			} catch (Exception e) {
				log.error("存储导文件错误",e);
				//e.printStackTrace();
				throw new FileStoreException(EasyjException.FileStoreError,"Oss存储文件错误。");
			}finally {
	            try {
					wb.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
	        }
		     
		 
		   //设置过期时间为1小时   
		    Date expiration=new Date(new Date().getTime()+3600*1000);
		        //生成URL
		    URL url=ossClient.generatePresignedUrl(ConstantProperties.ALIOSS_BUCKET_NAME,savePath,expiration);
		    // System.out.println(url.toString());
		    String urlstr= url.getProtocol()+"://"+url.getHost()+url.getPath();
		    
			// 关闭OSSClient。
			ossClient.shutdown();
				
		    return urlstr;	
		}
		

	    /**
	     * 上传excel到oss
	     *
	     * @param key oss的key
	     * @param wb  SXSSFWorkbook对象
	     * @throws Exception e
	   
	    private static void outputAsync(String key, SXSSFWorkbook wb) throws Exception {
	        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
	            wb.write(out);
	            ossClient.putObject(BUCKET_NAME, key, new ByteArrayInputStream(out.toByteArray()));
	        } finally {
	            wb.dispose();
	        }
	    }
		  */
		private  FileInfo localStore(MultipartFile file,String categoryDir) throws FileStoreException{
			FileInfo fl=new FileInfo();       
			String savePath =ConstantProperties.ALIOSS_FILE_PATH+"/";
			savePath=savePath+PathFormat.parse(categoryDir+"/{yyyy}{mm}{dd}/");
			
			//新文件名时间+8位rand数
			String uqstr=PathFormat.parse("{time}{rand:8}"); //// UUID.randomUUID().toString
			String originFileName=file.getOriginalFilename();
			String suffix = PathFormat.getSuffixByFilename(originFileName);
			String filename=uqstr+suffix;
			
	        savePath=savePath+filename;//filePath
			
			OSS ossClient = new OSSClientBuilder().build(ConstantProperties.ALIOSS_END_POINT, ConstantProperties.ALIOSS_ACCESS_KEY_ID, ConstantProperties.ALIOSS_ACCESS_KEY_SECRET);
					        
		    // 上传网络流。
		     try {
				ossClient.putObject(new PutObjectRequest(ConstantProperties.ALIOSS_BUCKET_NAME, savePath, file.getInputStream()));
			} catch (Exception e) {
				log.error("存储导文件错误",e);
				//e.printStackTrace();
				throw new FileStoreException(EasyjException.FileStoreError,"Oss存储文件错误。");
			}
		     
		 
		   //设置过期时间为1小时   
		    Date expiration=new Date(new Date().getTime()+3600*1000);
		        //生成URL
		    URL url=ossClient.generatePresignedUrl(ConstantProperties.ALIOSS_BUCKET_NAME,savePath,expiration);
		    // System.out.println(url.toString());
		    String urlstr= url.getProtocol()+"://"+url.getHost()+url.getPath();
		    
		    fl.setFilePath(savePath);
			fl.setSize(file.getSize());
			fl.setId(uqstr);
			fl.setUrl(urlstr);
			fl.setName(file.getOriginalFilename());
			
			// 关闭OSSClient。
			ossClient.shutdown();
				
		    return fl;		
		       
	  }		
		
		
	}	
	
	
}
